import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import json
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
import requests
from reqapi.api import BaseApi, ApiConfig
from com.db.order_account_manager import OrderAccountManager

@dataclass
class FilterItem:
    Name: str
    ValType: bool
    MaxVal: str
    MinVal: str
    FixedVal: str
    QueryString: str
    IsSelected: bool
    NodeItems: Optional[List['FilterItem']]
    PurchaseMaxPrice: Optional[str]
    SellPrice: Optional[str]
    LeasePrice: Optional[str]
    CategoryFlag: bool
    leaseTransferPrice: Optional[str]

@dataclass
class Filter:
    Name: str
    FilterKey: str
    ControlType: int
    FilterType: int
    IsShow: bool
    SubName: str
    MaxVal: str
    MinVal: str
    Items: Optional[List[FilterItem]]

@dataclass
class TemplateInfo:
    Id: int
    GameId: int
    CommodityName: str
    CommodityHashName: str
    GroupHashName: str
    IconUrl: str
    IconUrlLarge: str
    SteamPrice: str
    SteamUSDPrice: str
    MinPrice: str
    LeaseUnitPrice: str
    LongLeaseUnitPrice: str
    LeaseDeposit: str
    OnSaleCount: int
    OnLeaseCount: int
    PurchaseCount: int
    TypeName: str
    Rarity: str
    RarityColor: str
    Quality: str
    QualityColor: str
    Exterior: str
    ExteriorColor: str
    IsDoppler: int
    IsFade: int
    IsHardened: int
    rent: Optional[str] = None
    typeHashName: Optional[str] = None
    exteriorHashName: Optional[str] = None
    isSpecial: Optional[int] = None
    weaponHashName: Optional[str] = None
    exteriorId: Optional[int] = None
    minReferencePrice: Optional[int] = None
    ultraLongLeaseNumber: Optional[int] = None
    haveBox: Optional[int] = None
    showPrintGunSearch: Optional[int] = None
    templateTags: Optional[str] = None
    transferSellNumber: Optional[str] = None
    transferMinPrice: Optional[str] = None
    transferSellNumberText: Optional[str] = None
    jumpSteamLinkUrl: Optional[str] = None
    templateGroupAttrName: Optional[str] = None
    needFilter: Optional[bool] = None
    standardFlag: Optional[bool] = None
    IsFavorite: Optional[bool] = None
    ClassId: Optional[str] = None
    InstanceId: Optional[str] = None
    SteamPriceUpdate: Optional[str] = None
    SteamMarkeTable: Optional[str] = None
    BuffMinPrice: Optional[str] = None
    LeasePriceScale: Optional[str] = None
    Tags: Optional[str] = None
    From: Optional[str] = None
    Attr: Optional[str] = None
    LastOnShelfTime: Optional[str] = None
    HaveSold: Optional[str] = None
    HaveLease: Optional[str] = None

@dataclass
class SortConfig:
    sortTypeKey: str
    sortDesc: str
    showName: str

@dataclass
class AbradeRange:
    ShowName: str
    Name: str
    MaxVal: str
    MinVal: str

@dataclass
class ExteriorItem:
    """外观商品数据"""
    Name: str  # 商品名称
    leaseTransferPrice: Optional[str]  # 租赁转售价格
    ValType: bool  # 值类型
    MaxVal: str  # 最大值
    MinVal: str  # 最小值
    FixedVal: str  # 固定值
    QueryString: str  # 查询字符串
    IsSelected: bool  # 是否选中
    PurchaseMaxPrice: Optional[str]  # 最高求购价
    SellPrice: Optional[str]  # 出售价格
    LeasePrice: Optional[str]  # 租赁价格
    CategoryFlag: bool  # 分类标志

@dataclass
class TemplateResponse:
    Filters: List[Filter]
    TemplateInfo: TemplateInfo
    SellSortConfigList: List[SortConfig]
    LeaseSortConfigList: List[SortConfig]
    PreSaleSortConfigList: List[SortConfig]
    BuyPriceSortList: List[SortConfig]
    AbradeRangeList: List[AbradeRange]
    MergeFlag: int
    PriceTrendsFlag: int
    AutoDelivery: int

class GetTemplateInfoApi(BaseApi):
    """获取商品模板详情API"""
    
    def __init__(self, device_id, device_token, auth_token, uk):
        super().__init__(device_id, device_token, auth_token, uk)

    def execute(self, template_id, game_id=730, user_id=None):
        """
        执行API请求获取商品模板详情
        
        Args:
            template_id: 商品模板ID
            game_id: 游戏ID，默认730(CSGO)
            user_id: 用户ID，可选
            
        Returns:
            TemplateResponse: 结构化的响应数据
            None: 请求失败
        """
        url = f"{self.BASE_URL}/api/homepage/v2/detail/template/info"
        # 请求数据
        data = {
            "appVersion": ApiConfig.APP_VERSION,
            "gameId": ApiConfig.GAME_ID,
            "supportFilterShowName": 3,
            "templateId": template_id,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('Code') != 0:
                print(f"API返回错误: {result.get('Msg', '未知错误')}")
                print(f"完整响应: {result}")
                return None
            response_data = result.get('Data', {})
            template_response = TemplateResponse(
                Filters=[Filter(**f) for f in response_data.get('Filters', [])],
                TemplateInfo=TemplateInfo(**response_data.get('TemplateInfo', {})),
                SellSortConfigList=[SortConfig(**s) for s in response_data.get('SellSortConfigList', [])],
                LeaseSortConfigList=[SortConfig(**s) for s in response_data.get('LeaseSortConfigList', [])],
                PreSaleSortConfigList=[SortConfig(**s) for s in response_data.get('PreSaleSortConfigList', [])],
                BuyPriceSortList=[SortConfig(**s) for s in response_data.get('BuyPriceSortList', [])],
                AbradeRangeList=[AbradeRange(**a) for a in response_data.get('AbradeRangeList', [])],
                MergeFlag=response_data.get('MergeFlag', 0),
                PriceTrendsFlag=response_data.get('PriceTrendsFlag', 0),
                AutoDelivery=response_data.get('AutoDelivery', 0)
            )
            return template_response
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None

    def get_exterior_items(self, template_id: int, game_id: int = 730) -> Optional[List[ExteriorItem]]:
        """
        获取商品外观列表数据
        
        Args:
            template_id: 商品模板ID
            game_id: 游戏ID，默认730(CSGO)
            
        Returns:
            List[ExteriorItem]: 外观商品列表
            None: 获取失败
        """
        response = self.execute(template_id, game_id)
        if not response:
            return None
            
        # 查找外观(Exterior)过滤器
        exterior_filter = next(
            (f for f in response.Filters if f.FilterKey == "Exterior"),
            None
        )
        
        if not exterior_filter or not exterior_filter.Items:
            return None
            
        # 转换为ExteriorItem列表
        return [ExteriorItem(
            Name=item["Name"],
            leaseTransferPrice=item.get("leaseTransferPrice"),
            ValType=item["ValType"],
            MaxVal=item["MaxVal"],
            MinVal=item["MinVal"],
            FixedVal=item["FixedVal"],
            QueryString=item["QueryString"],
            IsSelected=item["IsSelected"],
            PurchaseMaxPrice=item.get("PurchaseMaxPrice"),
            SellPrice=item.get("SellPrice"),
            LeasePrice=item.get("LeasePrice"),
            CategoryFlag=item["CategoryFlag"]
        ) for item in exterior_filter.Items]

def main():
    """
    主函数，用于调试API
    """
    # 从请求信息中获取的认证数据
    account_manager = OrderAccountManager()
    account = account_manager.get_account_by_id(1)
        
    if not account:
        print("无法获取ID为1的账号")
        return
        
    device_id = account.get('device_id', '')
    auth_token = account.get('uu_token', '')
    uk = account.get('uk', '')
    
    # 创建API实例
    api = GetTemplateInfoApi(
        device_id=device_id,
        device_token=device_id,
        auth_token=auth_token,
        uk=uk
    )
    
    try:
        # 获取模板ID为837的商品外观列表
        exterior_items = api.get_exterior_items(template_id=837)
        
        if exterior_items:
            print("\n获取到的外观列表:")
            print("-" * 50)
            
            for item in exterior_items:
                print(f"外观名称: {item.Name}")
                if item.SellPrice:
                    print(f"出售价格: {item.SellPrice}")
                if item.LeasePrice:
                    print(f"租赁价格: {item.LeasePrice}")
                if item.PurchaseMaxPrice:
                    print(f"最高求购价: {item.PurchaseMaxPrice}")
                if item.leaseTransferPrice:
                    print(f"租赁转售价格: {item.leaseTransferPrice}")
                print(f"是否选中: {item.IsSelected}")
                print("-" * 50)
        else:
            print("获取外观列表失败")
            
    except Exception as e:
        print(f"运行出错: {str(e)}")

if __name__ == "__main__":
    main()
